package com.hntech.util;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.nio.charset.Charset;
import java.util.List;

/**
 * @Autho changqi.wu
 * @Date 路在脚下，使劲踩！
 */
public class IOUtil {

    public static final Charset CHARSET_UTF8 = Charset.forName("UTF-8");

    public static String readLineInputStream(InputStream inputStream) {

        try {
            return IOUtils.toString(inputStream,CHARSET_UTF8);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String readInputStream(InputStream inputStream) {

        try {

            byte[] bt = new byte[1024 * 10];  //每次读取10K
            int len = 0;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            while ((len = inputStream.read(bt)) != -1) {
                bos.write(bt, 0, len);
            }
            byte[] ba = bos.toByteArray();
            bos.close();
            return new String(ba, CHARSET_UTF8);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String readSocketInputStream(InputStream inputStream) {

        try {

            byte[] bt = new byte[1024 * 10];  //每次读取10K

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int len = inputStream.read(bt);
            if (len != -1) {
                bos.write(bt, 0, len);
            }
            byte[] ba = bos.toByteArray();
            bos.close();
            return new String(ba, CHARSET_UTF8);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static byte[] stringToByte(String str) {
        if (str == null) {
            return null;
        }
        return str.getBytes(CHARSET_UTF8);
    }


    public static void main(String[] args) {

//        StringBufferInputStream ss = new StringBufferInputStream("123456xxxx");
//        System.out.println(readInputStream(ss));

        ByteArrayInputStream bis = new ByteArrayInputStream("123456xxxx".getBytes());
        System.out.println(readInputStream(bis));
    }
}
